#include "shell.h"

/**
 * @brief construct argc argv style params from comand line
 *
 * @param cmd the command string from shell input
 * @param limit the maximum argv can be saved
 * @param argc the address to save arg count
 * @param argv the char* array to save arg values
 * @note  caller must ensure there has enough space to save string address
 */
void construct_param(char *cmd, int limit, int *argc, char **argv)
{
    char *ptr = cmd;
    int argcnt = 0;
    enum state {
        PARSING,
        FLYING
    } fsm;

    fsm = FLYING;

    while (*ptr)
    {
        switch (fsm)
        {
        case PARSING:
            if(*ptr == ' ')
            {
                fsm = FLYING;
                *ptr = '\0';
                if (argcnt < limit)
                {
                    *(argv + argcnt) = cmd;
                }
                argcnt++;
            }
            break;
        case FLYING:
            if (*ptr != ' ')
            {
                fsm = PARSING;
                cmd = ptr;
            }
            break;
        default:
            // error
            break;
        }
        ptr++;
    }
    if (fsm == PARSING)
    {
        if (argcnt < limit)
        {
            *(argv + argcnt) = cmd;
        }
        argcnt++;
    }
    *argc = argcnt;
}
